package com.android.sq.zouqi.bdmap;

import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.sq.zouqi.Constants;
import com.android.sq.zouqi.R;
import com.android.sq.zouqi.event.pTableEventInfo;
import com.android.sq.zouqi.pushservice.PushService;
import com.android.sq.zouqi.user.pTableUserInfo;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;

public class pScrEventMap extends MapActivity implements OnClickListener {
	private final static String TAG = "pScrEventMap";
	
	private int pCurEventId;
	private int pUserId;
	
	private BMapApp app;
	private MapView mapView;
	private List<GeoPoint> participants_geo_list;
	
	private List<Overlay> mapOverlays;					// 即MapView中所存有的Overlay图层都是放在这里的
	public MapController mapCtrl;						// 地图控制器	
	private MKSearch mSearch;							// 百度地图搜索模块
	private LocationListener locationListener;
	private Drawable pin;								// 图钉图片资源
	private ParticipantOverlay participant_overlay;		// 定位修改，用图钉显示这个位置
	public View participantPopView;
	public View participantPopView2;
	int iZoom = 0;
	
	private GeoPoint myloc_point;
	
	/*
	 * 需要维护的数据 - 参与人的列表、活动信息
	 */
	private int participants_total;
	private List<pTableUserInfo> pCurrentParticipants;
	private pTableEventInfo pCurrentEvent;
	private ParticipantInfo pInfo_arr[];
	
	/*
	 * Handler 消息
	 */
	public final static int GET_FRIEND_LOCATION_INFO = 0X0000;		// 当从推送服务中获取朋友的定位信息，用于显示实时的位置信息
	public final static int SEND_MY_LOCATION_INFO = 0X0001;		// 把自己的方位信息通过PushService的actionSendMsgToTopic方法发送到所有活动参与人的手机端
	
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int action = msg.what;
			switch (action) {
			case GET_FRIEND_LOCATION_INFO :
				Bundle bundle = msg.getData();
				int participant_id = bundle.getInt("PARTICIPANT_ID");
				double participant_loc_point[] = bundle.getDoubleArray("PARTICIPANT_LOC");
				GeoPoint participant_geo_point = new GeoPoint((int)(participant_loc_point[0] * 1e6), 
							(int)(participant_loc_point[1] * 1e6));
				for (int i = 0; i < participants_total; i++) {
					if (participant_id == pInfo_arr[i].id) {
						participant_overlay.removeOverlay(pInfo_arr[i].index_in_overlay);
						OverlayItem overlay_item = new OverlayItem(participant_geo_point, null, "" + participant_id);
						participant_overlay.addOverlay(i, overlay_item);
						participant_overlay.updateOverlay();
					}
				}
				Log.e(TAG, "收到参与人" + participant_id + "的方位信息，已经更新，现在图层的长度为" + participant_overlay.size());
				break;
			case SEND_MY_LOCATION_INFO:
				GeoPoint point = (GeoPoint)msg.obj;
				sendMyLocationToEvent(pCurEventId, point);
				break;
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		setContentView(R.layout.scrmain_event_map);
		// 通知全局的Application，现在运行的是pScrEventMap，它当前展示的是活动***的情况
		app = (BMapApp)this.getApplication();
		Log.e(TAG, "pCurEventId = " + pCurEventId);
		//app.setActivityInfo(Constants.ACTIVTIY_pScrEventMap, pCurEventId);
		
		app.scrEventMap = this;
		
		SharedPreferences share = app.getSharedPreferences("USER_INFO", Context.MODE_PRIVATE);
		pUserId = share.getInt(Constants.SP_USER_ID, 0);
		
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new BMapApp.MyGeneralListener());
		}
		app.mBMapMan.start();
        // 如果使用地图SDK，请初始化地图Activity
        super.initMapActivity(app.mBMapMan);
        // 初始化与MapView相关的一些变量
        mapView = (MapView)findViewById(R.id.bmapView);
		mapCtrl = mapView.getController();
        mapView.setBuiltInZoomControls(true);
        mapView.setDrawOverlayWhenZooming(true);	//设置在缩放动画过程中也显示overlay,默认为不绘制
		iZoom = mapView.getZoomLevel();
		mapOverlays = mapView.getOverlays();
		
		initParticipantPopView();		// 创建点击图钉的弹出泡泡
		// 得到用于标注当前活动地点的图标资源-图钉pin，并为图钉定义位置和边界
     	pin = getResources().getDrawable(R.drawable.iconmarka);
     	pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight());
		
		participant_overlay = new ParticipantOverlay(pin, participantPopView);
		//mapOverlays.add(participant_overlay);
		
		getBundleData();	// 获取上一个Act的数据
		participant_overlay.updateOverlay();
		mapOverlays.add(participant_overlay);
		
		// 注册定位监听模块
        locationListener = new LocationListener() {
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				if(location != null){
					// 获取到定位之后，手持者的地理经纬度，并传送给handler进行UI更新展示
					myloc_point = new GeoPoint((int)(location.getLatitude()*1e6), 
							(int)(location.getLongitude()*1e6));
					//Log.e(TAG, "GPS定位获取的经纬度:" + myloc_point.toString());
					//mapCtrl.animateTo(myloc_point);
					
					// 如果您就是当前活动的发起人，就不用进行方位信息的推送了，直接再地图上进行显示
					if (pCurrentEvent.getpEventOwnerId() == pUserId) {
						
					} else {	// 如果是活动参与人，需要进行方位信息的推送
						// 把当前位置myloc_point用Handler发送给PushService去处理，
						// 即调用PushService.actionSendMsgToTopic(主题， 消息);
						Message msg = new Message();
						msg.what = SEND_MY_LOCATION_INFO;
						msg.obj = myloc_point;
						handler.sendMessage(msg);
					}
					// 并取消定位的监听，否则会10s定位一次
					//app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);

				}
			}
        };
	}
	
	// 把我的位置通过PushService发送给好友
	public void sendMyLocationToEvent(int event_id, GeoPoint point) {
		// 发送给zouqi/event_*/geo主题的消息形式：参与人id:纬度:经度
		String msg = pUserId + ":"+ point.getLatitudeE6() + 
				"," + point.getLongitudeE6();
		String topic = PushService.MQTT_TOPIC + "/event_" + event_id + "/geo";
		//Log.e(TAG, "我上传的位置是(event_"+event_id+"):" + msg);
		PushService.actionSendMsgToTopic(topic, msg);
	}
	
	// 用于把一个参与人的位置显示出来
	private void addParticipantToMap(OverlayItem item) {
		/*MapView.LayoutParams params = (MapView.LayoutParams) participantPopView.getLayoutParams();
		params.x = participant_overlay.layout_x;	//Y轴偏移
		params.y = participant_overlay.layout_y;	//Y轴偏移
		params.point = item.getPoint();*/
		
		/*mapView.updateViewLayout(participantPopView,
                new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                		item.getPoint(), MapView.LayoutParams.BOTTOM_CENTER));*/
		
		/*TextView participant_name_tv = (TextView) participantPopView.findViewById(R.id.participant_name);
		participant_name_tv.setText(item.getTitle());*/
		
		//RelativeLayout button = (RelativeLayout) participantPopView.findViewById(R.id.loc_btn);
		//button.setOnClickListener(this);
		//mapView.updateViewLayout(participantPopView, params);
		//participantPopView.setVisibility(View.VISIBLE);
		participant_overlay.addOverlay(item);
		//mapCtrl.animateTo(item.getPoint());
		//participant_overlay.updateOverlay();
	}
	
	public void getBundleData() {
		/*Bundle bundle = this.getIntent().getExtras();
		double loc_point[] = bundle.getDoubleArray(Constants.PIN_GEOPOINT);
		pin_address = bundle.getString(Constants.PIN_ADDRESS);
		if (loc_point[0] == -90) {
			isDataNull = true;
		} else {
			isDataNull = false;
			pin_point = new GeoPoint((int)(loc_point[0] * 1e6), (int)(loc_point[1] * 1e6));
			pin_overlay_item = new OverlayItem(pin_point, "活动地址", pin_address);
		}*/
		// 从上一个pScrMain中获取传递参数
		pCurrentEvent = new pTableEventInfo();
		
		Bundle bundle = this.getIntent().getExtras();
		int cur_event_id = bundle.getInt("CURRENT_EVENT_ID");
		int cur_event_owner_id = bundle.getInt("CURRENT_EVENT_OWNER_ID");
		this.pCurrentEvent.set_id(cur_event_id);
		this.pCurrentEvent.setpEventOwnerId(cur_event_owner_id);
		pCurEventId = cur_event_id;
		
		// 通知App，现在正在运行的是pScrEventMap这个Activity，并且传递相关数据为：这个活动id
		app.setActivityInfo(Constants.ACTIVTIY_pScrEventMap, pCurEventId);
		
		// 模拟数据
		participants_total = 2;
		int count = 0;
		int participants_id_arr[] = {650, 651};
		pInfo_arr = new ParticipantInfo[participants_total];
		for (int i = 0; i < participants_total; i++) {
			ParticipantInfo p = new ParticipantInfo(participants_id_arr[i], i);
			pInfo_arr[i] = p;
			GeoPoint gp = new GeoPoint(30256121 + 100 * count, 120189234 + 100 * count++);
			mapCtrl.animateTo(gp);
			OverlayItem participant_overlayItem = new OverlayItem(gp, "" + pInfo_arr[i].id,
					"name");
			addParticipantToMap(participant_overlayItem);
			Log.e(TAG, "添加" + pInfo_arr[i].id + "成功");
		}
		//mapOverlays.add(participant_overlay);
	}
	
	public void initParticipantPopView() {
		if(null == participantPopView){
			participantPopView = getLayoutInflater().inflate(R.layout.overlay_participantpop, null);
			mapView.addView(participantPopView, new MapView.LayoutParams(
					MapView.LayoutParams.WRAP_CONTENT,
					MapView.LayoutParams.WRAP_CONTENT, null,
					MapView.LayoutParams.BOTTOM_CENTER));
			participantPopView.setVisibility(View.GONE);
    	} else {
    		Log.e(TAG, "PopView 不是为空");
    	}
	}
	
	public void registMyLocation() {
			Log.e(TAG, "定位我的位置");
			app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
			//myloc_overlay.enableMyLocation();
			Log.e(TAG, "locMyPosition完成");
	}
	
	// 修改某一个好友在MapView上的位置
	public void updateFriendLocation(String msg) {
		Log.e(TAG, "更新好友的位置- msg=" + msg);
		int maohao_of_index = msg.indexOf(":");
		int douhao_of_index = msg.indexOf(",");
		int participant_id = Integer.parseInt(msg.substring(0, maohao_of_index));
		int latitudeInt = Integer.parseInt(msg.substring(maohao_of_index + 1, douhao_of_index));
		int longitudeInt = Integer.parseInt(msg.substring(douhao_of_index + 1));
		int participant_loc_point[] = {latitudeInt, longitudeInt};
		GeoPoint participant_geo_point = new GeoPoint(participant_loc_point[0], 
					participant_loc_point[1]);
		for (int i = 0; i < participants_total; i++) {
			if (participant_id == pInfo_arr[i].id) {
				//Log.e(TAG, "更新了好友" + pInfo_arr[i].id + "的位置为：" + msg);
				Log.e(TAG, "更新了好友" + participant_id + ", latitudeInt = " + latitudeInt + ", longitude = " + longitudeInt);
				participant_overlay.removeOverlay(pInfo_arr[i].index_in_overlay);
				Log.e(TAG, "remove, participant_overlay size = " + participant_overlay.size());
				OverlayItem overlay_item = new OverlayItem(participant_geo_point, "" + participant_id, null);
				participant_overlay.addOverlay(i, overlay_item);
				participant_overlay.updateOverlay();
			}
		}
		
		mapView.invalidate();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mapView) {
			
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onPause() {
		BMapApp app = (BMapApp)this.getApplication();
		//app.mBMapMan.getLocationManager().removeUpdates(locationListener);
		
		//myloc_overlay.disableMyLocation();
		//myloc_overlay.disableCompass(); // 关闭指南针
		if(app.mBMapMan != null)
			app.mBMapMan.stop();
		super.onPause();
	}
	@Override
	protected void onResume() {
		BMapApp app = (BMapApp)this.getApplication();
		app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
		app.mBMapMan.start();
		super.onResume();
	}
	
	/*
	 * 这是一个类，包含一个参与人的id和他在OverlayList列表中的位置
	 */
	class ParticipantInfo {
		int id;					// 参与人id
		int index_in_overlay;	// 参与人再overlaylist中的位置
		public ParticipantInfo(int id, int index) {
			this.id = id;
			this.index_in_overlay = index;
		}
		public int getIndex_in_overlay() {
			return index_in_overlay;
		}
		public void setIndex_in_overlay(int index_in_overlay) {
			this.index_in_overlay = index_in_overlay;
		}
	}
}
